/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * 个人信息
 */
import React, {Component} from "react";
import {
    StyleSheet,
    TouchableOpacity,
    Dimensions,
    Image,
    View,
    ToastAndroid,
    ScrollView,
    Button,
    Text,
    TextInput,
    SafeAreaView,
    DeviceEventEmitter,
    BackHandler,
    Platform
} from "react-native";
import moment from "moment";
import ItemCell from "../../../widget/ItemCell";
import DateTimePicker from "react-native-modal-datetime-picker";
import MineAvatorPhotoDialog from "../../../widget/dialog/MineAvatorPhotoDialog";
import MineNameDialog from "../../../widget/dialog/MineNameDialog";
import MineRealNameDialog from "../../../widget/dialog/MineRealNameDialog";
import MineSchoolDialog from "../../../widget/dialog/MineSchoolDialog";
import MineSexDialog from "../../../widget/dialog/MineSexDialog";
import MineEditPhoneDialog from "../../../widget/dialog/MineEditPhoneDialog";
import MineEditNextPhoneDialog from "../../../widget/dialog/MineEditNextPhoneDialog";
import MineSubjectModal from "../../../widget/mine/MineSubjectModal";
import color from "../../../widget/color";
import api from "../../../api/api";
import method from "../../../api/method";
import {fetchPostRequest} from "../../../api/NetworkTool";
// import Toast, {DURATION} from 'react-native-easy-toast'


const {width} = Dimensions.get('window');
type Props = {
    navigation:any,
}
export default class PersonalMateralScene extends Component<Props> {
    static navigationOptions = ({navigation}: any) => ({

        headerTintColor: 'black',
        title: '个人资料',
        headerRight: <Text/>,
        headerLeft: <TouchableOpacity onPress={()=>{
            navigation.state.params.callback('回调参数');
            navigation.goBack()
        }}>
            <Image style={{marginLeft:12}} source={require('../../../../res/img/gobal_back.png')}/>
        </TouchableOpacity>
    })


    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress',
            this.onBackButtonPressAndroid());
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress',
            this.onBackButtonPressAndroid());
    }

    onBackButtonPressAndroid = () => {
        this.props.navigation.state.params.callback('回调参数');
        this.props.navigation.goBack()
    }

    //构造函数
    constructor(props) {
        super(props);
        const {profile} = this.props.navigation.state.params
        this.state = {
            sections: [
                {name: '一年级', grade: 'primary_1'}, {name: '二年级', grade: 'primary_2'}, {
                    name: '三年级',
                    grade: 'primary_3'
                }, {name: '四年级', grade: 'primary_4'}, {name: '五年级', grade: 'primary_5'}, {
                    name: '六年级',
                    grade: 'primary_6'
                },
                {name: '初一', grade: 'middle_1'}, {name: '初二', grade: 'middle_2'}, {name: '初三', grade: 'middle_3'},
                {name: '高一', grade: 'heigh_1'}, {name: '高二', grade: 'heigh_2'}, {name: '高三', grade: 'heigh_3'},
            ],
            avatarSource: {uri: profile.portrait},
            showModal: false,
            showSharePop: false,//分享弹窗，默认不显示
            showPhoto: false,
            mobile: profile.mobile,
            showName: false,
            name: profile.nickname,
            showSex: false,
            sex: profile.gender == 'male' ? '男' : '女',
            showPhone: false,
            showNextPhone: false,
            isDateTimePickerVisible: false,
            // birth: profile.birthday.substr(0,10),
            birth: profile.birthday == null ? '' : profile.birthday.substr(0, 10),
            showGrade: false,
            grade: '一年级',
            realname: profile.realname,
            fileUrl: profile.portrait,
            grade_id: profile.grade,
            school: profile.school == null ? '' : profile.school,
            showSchool: false,
            showRealName: false,

        };
    }

    componentDidMount() {
        const {profile} = this.props.navigation.state.params

        this.state.sections.forEach(info => {
            if (info.grade == profile.grade) {
                this.setState({grade: info.name})
            }
        })
    }

    _showDateTimePicker = () => this.setState({isDateTimePickerVisible: true});

    _hideDateTimePicker = () => this.setState({isDateTimePickerVisible: false});

    _handleDatePicked = (date) => {
        console.log('A date has been picked: ', date);
        this.setState({birth: moment(date).format('YYYY-MM-DD')})
        this._hideDateTimePicker();
        let params = {
            birthday: moment(date).format('YYYY-MM-DD'),
        }
        this.updateUserProfile(params)
    };

    selectSubject(value) {
        this.setState({showGrade: !this.state.showGrade});
        if (value != this.state.grade) {
            this.setState({grade: value.name, grade_id: value.grade});
            let params = {
                grade: value.grade,
            }
            this.updateUserProfile(params)
        }
    }

    renderView() {
        return (
            <SafeAreaView style={{flex: 1, backgroundColor: 'white'}}>
                <ScrollView>
                    <View>

                        <TouchableOpacity onPress={() => this.setState({showPhoto: true})}>
                            <View style={[styles.avertStyle]}>
                                <Text style={{fontSize: 14, color: 'black',fontWeight:'bold',}}>头像</Text>
                                <View style={{flex: 1, backgroundColor: 'blue'}}/>
                                <Image source={this.state.avatarSource}
                                       style={{width: 55, height: 55, borderRadius: 27.5}}/>
                                <Image style={styles.arrow} source={require('../../../../res/img/icon_arrow.png')}/>
                            </View>

                        </TouchableOpacity>
                        <View style={{height: 0.5, marginLeft: 12, width: width - 24, backgroundColor: '#DFDFDF'}}/>
                        <TouchableOpacity onPress={() => this.setState({showName: true})}>
                            <ItemCell title='昵称' subtitle={this.state.name} arrow={true}/>
                        </TouchableOpacity>
                        <View style={{height: 0.5, marginLeft: 12, width: width - 24, backgroundColor: '#DFDFDF'}}/>
                        <TouchableOpacity onPress={() => {
                        this.setState({showRealName: true})
                    }}>
                            <ItemCell title='真实姓名' subtitle={this.state.realname} arrow={true}/>
                        </TouchableOpacity>
                        <View style={{height: 0.5, marginLeft: 12, width: width - 24, backgroundColor: '#DFDFDF'}}/>
                        <TouchableOpacity onPress={() => this.setState({showSex: true})}>
                            <ItemCell title='性别' subtitle={this.state.sex} arrow={true}/>
                        </TouchableOpacity>
                        <View style={{height: 0.5, marginLeft: 12, width: width - 24, backgroundColor: '#DFDFDF'}}/>
                        <TouchableOpacity onPress={this._showDateTimePicker}>
                            <ItemCell title='出生日期' subtitle={this.state.birth} arrow={true}/>
                        </TouchableOpacity>
                        <View style={{height: 0.5, marginLeft: 12, width: width - 24, backgroundColor: '#DFDFDF'}}/>
                        <TouchableOpacity onPress={() => {
                        this.setState({showPhone: true})
                    }}>
                            <ItemCell title='联系电话' subtitle={this.state.mobile} arrow={true}/>
                        </TouchableOpacity>
                        <View style={{height: 0.5, marginLeft: 12, width: width - 24, backgroundColor: '#DFDFDF'}}/>
                        <TouchableOpacity onPress={() => this.setState({showGrade: true})}>
                            <ItemCell title='年级' subtitle={this.state.grade} arrow={true}/>
                        </TouchableOpacity>
                        <View style={{height: 0.5, marginLeft: 12, width: width - 24, backgroundColor: '#DFDFDF'}}/>
                        <TouchableOpacity onPress={() => this.setState({showSchool: true})}>
                            <ItemCell title='所在学校' subtitle={this.state.school} arrow={true}/>
                        </TouchableOpacity>
                        <View style={{height: 0.5, marginLeft: 12, width: width - 24, backgroundColor: '#DFDFDF'}}/>


                        <MineAvatorPhotoDialog show={this.state.showPhoto} avatar={this.state.avatarSource}
                                               callbackAvatar={(avatar) => {
                                               this.setState({avatarSource: avatar.avatarSource,fileUrl:avatar.fileUrl})
                                               let params = {
                                                   headshot:avatar.fileUrl,
                                               }
                                               this.updateUserProfile(params)
                                           }} closeModal={(show) => {
                        this.setState({showPhoto: show})
                    }} {...this.props}/>
                        <MineNameDialog show={this.state.showName} name={this.state.name} closeModal={(show) => {
                        this.setState({showName: show})
                    }} callbackName={(text) => {
                        this.setState({name: text})
                        let params = {
                            nickname:text,
                        }
                        this.updateUserProfile(params)
                    }} {...this.props}/>
                        <MineRealNameDialog show={this.state.showRealName} name={this.state.realname} closeModal={(show) => {
                        this.setState({showRealName: show})
                    }} callbackName={(text) => {
                        this.setState({realname: text})
                        let params = {
                            realname:text,
                        }
                        this.updateUserProfile(params)
                    }} {...this.props}/>
                        <MineSexDialog show={this.state.showSex} sex={this.state.sex} closeModal={(show) => {
                        this.setState({showSex: show})
                    }} callbackSex={(text) => {
                        this.setState({sex: text})

                        let gender = text == '男' ? 'male':'female'
                        let params = {
                            gender:gender,
                        }
                        this.updateUserProfile(params)
                    }} {...this.props}/>
                        <MineEditPhoneDialog show={this.state.showPhone} closeModal={(show) => {
                        this.setState({showPhone: show})
                    }} nextModal={() => {
                        this.setState({showNextPhone: true})
                    }}  {...this.props}/>
                        <MineEditNextPhoneDialog show={this.state.showNextPhone} closeModal={(show) => {
                        this.setState({showNextPhone: show})
                    }} callBackPhone={(phone)=>{
                        this.setState({mobile:phone})
                    }} {...this.props}/>
                        <DateTimePicker
                            isVisible={this.state.isDateTimePickerVisible}
                            titleIOS={'选择时间'}
                            mode={'date'}
                            cancelTextIOS='取消'
                            confirmTextIOS='确定'
                            maximumDate={new Date()}
                            onConfirm={this._handleDatePicked}
                            onCancel={this._hideDateTimePicker}
                        />
                        <MineSubjectModal subject_title={this.state.grade} isShow={this.state.showGrade}
                                          callbackSubject={(item)=>{
                                              if (item){
                                                  this.selectSubject(item)
                                              }

                    }}/>
                        <MineSchoolDialog show={this.state.showSchool} name={this.state.school} closeModal={(show) => {
                        this.setState({showSchool: show})
                    }} callbackName={(text) => {
                        this.setState({school: text})
                        let params = {
                            school:text,
                        }
                        this.updateUserProfile(params)
                    }} {...this.props}/>
                    </View>
                </ScrollView>
            </SafeAreaView>
        )
    }

    // bao_cun(){
    //     if (this.state.mobile){
    //         return <TouchableOpacity onPress={()=>{this.updateUserProfile()}} style={styles.enable_bao_cun}>
    //             <Text style={{fontSize:16,fontWeight:'bold',color:'white'}}>保存</Text>
    //         </TouchableOpacity>
    //     }else {
    //         return <View style={styles.un_enable_bao_cun}>
    //             <Text style={{fontSize:16,fontWeight:'bold',color:'white'}}>保存</Text>
    //         </View>
    //     }
    //
    //
    // }
    updateUserProfile(params) {
        fetchPostRequest(api.updateUserProfile, method.post, params)
            .then(res => {
            })
            .catch(err => {
            })

    }

    render() {
        return (
            <View style={styles.flexStyle}>
                {this.renderView()}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    flexStyle: {
        flex: 1,
        width: width,
        flexDirection: 'column',
        backgroundColor: '#F9F9F9'
    },
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    avertStyle: {
        backgroundColor: '#ffffff',
        flexDirection: 'row',
        alignItems: 'center',
        paddingLeft: 12,
        paddingRight: 12,
        height: 95
    },
    arrow: {
        width: 14,
        height: 14,
        marginLeft: 5,
    },
    enable_bao_cun: {
        height: 50,
        backgroundColor: color.globalMainColor,
        alignItems: 'center',
        justifyContent: "center",
    },
    un_enable_bao_cun: {
        height: 50,
        backgroundColor: '#BBBABA',
        alignItems: 'center',
        justifyContent: "center",
    }

});

const photoOptions = {
    title: '请选择',
    quality: 0.8,
    cancelButtonTitle: '取消',
    takePhotoButtonTitle: '拍照',
    chooseFromLibraryButtonTitle: '选择相册',
    allowsEditing: true,
    noData: false,
    storageOptions: {
        skipBackup: true,
        path: 'images'
    }
};


